<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-flash.min.css?v=1.0.2" rel="stylesheet">




  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Jetpack,LiveData,">





  <link rel="alternate" href="/atom.xml" title="Colin's Blog" type="application/atom+xml">






<meta name="description" content="什么是 LiveData LiveData是一个可观察的数据持有者类。与常规 observable 不同，LiveData 是生命周期感知的，这意味着它遵从其他应用程序组件的生命周期，例如 Activity，Fragment 或 Service。此感知确保 LiveData 仅更新处于 Activity 生命周期状态应用程序组件的观察者。  使用 LiveData 的好处 既然有了 observa">
<meta name="keywords" content="Jetpack,LiveData">
<meta property="og:type" content="article">
<meta property="og:title" content="Jetpack 之 LiveData">
<meta property="og:url" content="http://duanyitao.com/2019/04/12/Jetpack-之-LiveData/index.html">
<meta property="og:site_name" content="Colin&#39;s Blog">
<meta property="og:description" content="什么是 LiveData LiveData是一个可观察的数据持有者类。与常规 observable 不同，LiveData 是生命周期感知的，这意味着它遵从其他应用程序组件的生命周期，例如 Activity，Fragment 或 Service。此感知确保 LiveData 仅更新处于 Activity 生命周期状态应用程序组件的观察者。  使用 LiveData 的好处 既然有了 observa">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-04-12T09:53:16.020Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Jetpack 之 LiveData">
<meta name="twitter:description" content="什么是 LiveData LiveData是一个可观察的数据持有者类。与常规 observable 不同，LiveData 是生命周期感知的，这意味着它遵从其他应用程序组件的生命周期，例如 Activity，Fragment 或 Service。此感知确保 LiveData 仅更新处于 Activity 生命周期状态应用程序组件的观察者。  使用 LiveData 的好处 既然有了 observa">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":20,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://duanyitao.com/2019/04/12/Jetpack-之-LiveData/">





  <title>Jetpack 之 LiveData | Colin's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Colin's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">时间是没有声音的锉刀。</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-android">
          <a href="/categories/Android/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-android"></i> <br>
            
            Android
          </a>
        </li>
      
        
        <li class="menu-item menu-item-kotlin">
          <a href="/categories/Kotlin/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-code"></i> <br>
            
            Kotlin
          </a>
        </li>
      
        
        <li class="menu-item menu-item-dart">
          <a href="/categories/Dart/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-terminal"></i> <br>
            
            Dart
          </a>
        </li>
      
        
        <li class="menu-item menu-item-flutter">
          <a href="/categories/Flutter/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-road"></i> <br>
            
            Flutter
          </a>
        </li>
      
        
        <li class="menu-item menu-item-ios">
          <a href="/categories/iOS/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-apple"></i> <br>
            
            iOS
          </a>
        </li>
      
        
        <li class="menu-item menu-item-web">
          <a href="/categories/Web/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-html5"></i> <br>
            
            Web
          </a>
        </li>
      
        
        <li class="menu-item menu-item-vim">
          <a href="/categories/Vim/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-code"></i> <br>
            
            Vim
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://duanyitao.com/2019/04/12/Jetpack-之-LiveData/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="段燚涛">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Colin's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Jetpack 之 LiveData</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-04-12T16:12:28+08:00">
                2019-04-12
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2019-04-12T17:53:16+08:00">
                2019-04-12
              </time>
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index">
                    <span itemprop="name">Android</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.6k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  6
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <h2 id="什么是-LiveData"><a href="#什么是-LiveData" class="headerlink" title="什么是 LiveData"></a>什么是 LiveData</h2><blockquote>
<p>LiveData是一个可观察的数据持有者类。与常规 observable 不同，LiveData 是生命周期感知的，这意味着它遵从其他应用程序组件的生命周期，例如 Activity，Fragment 或 Service。此感知确保 LiveData 仅更新处于 Activity 生命周期状态应用程序组件的观察者。</p>
</blockquote>
<h2 id="使用-LiveData-的好处"><a href="#使用-LiveData-的好处" class="headerlink" title="使用 LiveData 的好处"></a>使用 LiveData 的好处</h2><blockquote>
<p>既然有了 observable 系列的支持，那为什么还有 LiveData 存在的意义？正所谓存在的就是合理的，也当然就有它存在的理由，下面我们来看看 LiveData 相较于 Observable 有哪些优点：</p>
</blockquote>
<h3 id="UI-和数据保持一致性"><a href="#UI-和数据保持一致性" class="headerlink" title="UI 和数据保持一致性"></a>UI 和数据保持一致性</h3><p>  LiveData 遵循观察者模式。Observer 生命周期状态更改时，LiveData 会通知其观察的对象列表。每次应用程序数据更改时，观察者都可以在每次更改时收到消息并更新UI，而不是主动去获取状态来更新UI。</p>
<h3 id="没有内存泄漏"><a href="#没有内存泄漏" class="headerlink" title="没有内存泄漏"></a>没有内存泄漏</h3><p>  观察者绑定 Lifecycle 对象并在其相关生命周期被销毁后自行清理。</p>
<h3 id="不会因-UI-暂停而崩溃"><a href="#不会因-UI-暂停而崩溃" class="headerlink" title="不会因 UI 暂停而崩溃"></a>不会因 UI 暂停而崩溃</h3><p>  如果观察者的生命周期处于非活动（例如，在后台堆栈中的 Activity 的情况下），则它不会接收任何 LiveData 事件。</p>
<h3 id="不再需要手动管理生命周期"><a href="#不再需要手动管理生命周期" class="headerlink" title="不再需要手动管理生命周期"></a>不再需要手动管理生命周期</h3><p>  UI组件只是观察相关数据，不会停止或恢复观察。LiveData 自动管理所有这些动作，因为它可以感知到到相关的生命周期状态变化。</p>
<h3 id="始终保持最新数据"><a href="#始终保持最新数据" class="headerlink" title="始终保持最新数据"></a>始终保持最新数据</h3><p>  如果 UI 生命周期变为非活动，它将在再次变为活动时接收最新数据。例如，后台 Activity 在返回前台后立即接收最新数据。</p>
<h3 id="配置更改自动处理"><a href="#配置更改自动处理" class="headerlink" title="配置更改自动处理"></a>配置更改自动处理</h3><p>  如果由于配置更改（例如设备旋转）而重新创建 Activity 或 Fragment ，则会立即接收最新的可用数据。</p>
<h3 id="共享资源"><a href="#共享资源" class="headerlink" title="共享资源"></a>共享资源</h3><p>  您可以把 LiveData 使用单例模式来包装各种系统服务，以便可以在应用程序中共享它们。该 LiveData 对象连接到系统服务一次，然后任何需要该资源的观察者只需观察该 LiveData 对象，即可拿到共享的数据资源。</p>
<h2 id="如何使用-LiveDate-对象"><a href="#如何使用-LiveDate-对象" class="headerlink" title="如何使用 LiveDate 对象"></a>如何使用 LiveDate 对象</h2><blockquote>
<p>包括以下步骤：</p>
</blockquote>
<ol>
<li>创建一个 LiveData 用于保存特定类型数据的实例。这通常在您的 ViewModel 内完成 。</li>
<li>创建一个 Observer 定义 onChanged() 方法的对象，该对象负责处理 LiveData 对象数据更改时发出的数据。通常Observer 在 UI 控制器中创建，例如 Activity 或 Fragment 。</li>
<li>使用 LiveData 的 observe 方法将 Observer 绑定到 LiveData 对象。通常在UI控制器中完成绑定，例如 Activity 或 Fragment 。</li>
</ol>
<h3 id="创建-LiveData-对象"><a href="#创建-LiveData-对象" class="headerlink" title="创建 LiveData 对象"></a>创建 LiveData 对象</h3><blockquote>
<p>在 ViewModel 中创建 LiveData 对象：</p>
</blockquote>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">NameViewModel</span> : <span class="type">ViewModel</span></span>() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Create a LiveData with a String</span></span><br><span class="line">    <span class="keyword">val</span> currentName: MutableLiveData&lt;String&gt; <span class="keyword">by</span> lazy &#123;</span><br><span class="line">        MutableLiveData&lt;String&gt;()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="观察-LiveData-对象"><a href="#观察-LiveData-对象" class="headerlink" title="观察 LiveData 对象"></a>观察 LiveData 对象</h3><blockquote>
<p>在 UI 中观察 LiveData:</p>
</blockquote>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">NameActivity</span> : <span class="type">AppCompatActivity</span></span>() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">lateinit</span> <span class="keyword">var</span> model: NameViewModel</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onCreate</span><span class="params">(savedInstanceState: <span class="type">Bundle</span>?)</span></span> &#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState)</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Other code to setup the activity...</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// Get the ViewModel.</span></span><br><span class="line">        model = ViewModelProviders.of(<span class="keyword">this</span>).<span class="keyword">get</span>(NameViewModel::<span class="class"><span class="keyword">class</span>.<span class="title">java</span>)</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">// Create the observer which updates the UI.</span></span><br><span class="line">        <span class="keyword">val</span> nameObserver = Observer&lt;String&gt; &#123; newName -&gt;</span><br><span class="line">            <span class="comment">// Update the UI, in this case, a TextView.</span></span><br><span class="line">            nameTextView.text = newName</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.</span></span><br><span class="line">        model.currentName.observe(<span class="keyword">this</span>, nameObserver)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="更新-LiveData-对象"><a href="#更新-LiveData-对象" class="headerlink" title="更新 LiveData 对象"></a>更新 LiveData 对象</h3><blockquote>
<p>如果是在非主线程中更新数据，使用 postValue 方法</p>
</blockquote>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">button.setOnClickListener &#123;</span><br><span class="line">    <span class="keyword">val</span> anotherName = <span class="string">"John Doe"</span></span><br><span class="line">    model.currentName.postValue(anotherName)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>如果是在主线程中更新数据，使用 setValue 方法</p>
</blockquote>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">button.setOnClickListener &#123;</span><br><span class="line">    <span class="keyword">val</span> anotherName = <span class="string">"John Doe"</span></span><br><span class="line">    model.currentName.setValue(anotherName)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="LiveData-高级部分"><a href="#LiveData-高级部分" class="headerlink" title="LiveData 高级部分"></a>LiveData 高级部分</h2><h3 id="在-Room-中使用-LiviData"><a href="#在-Room-中使用-LiviData" class="headerlink" title="在 Room 中使用 LiviData"></a>在 Room 中使用 LiviData</h3><p>Room 持久库支持可观察的查询操作，返回 LiveData 对象，可观察的查询写在 DAO 中并成为 DAO 的一部分。<br>Room 将自动生成所有需要的中间代码，以达到数据库被更新时自动发出通知，所生成的中间代码运行在异步线程中，如果你的界面显示的数据源来自 Room，这个特性将显得非常有用。</p>
<h3 id="扩展-LiviData"><a href="#扩展-LiviData" class="headerlink" title="扩展 LiviData"></a>扩展 LiviData</h3><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">StockLiveData</span></span>(symbol: String) : LiveData&lt;BigDecimal&gt;() &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">val</span> stockManager = StockManager(symbol)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">val</span> listener = &#123; price: BigDecimal -&gt;</span><br><span class="line">        value = price</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onActive</span><span class="params">()</span></span> &#123;</span><br><span class="line">        stockManager.requestPriceUpdates(listener)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onInactive</span><span class="params">()</span></span> &#123;</span><br><span class="line">        stockManager.removeUpdates(listener)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>如上所示，如果需要扩展一个 LiveData 对象，我们需要实现以下方法：</p>
</blockquote>
<ul>
<li><p>onActive() 当 LiveData 对象的观察者处于活动状态时调用该方法。</p>
</li>
<li><p>onInactive() 当 LiveData 对象的所有观察者都处于非活动状态时调用该方法。</p>
</li>
<li><p>setValue(T) 此方法 LiveData 实例的值发生更新时调用，并通知所有活动的观察者。</p>
</li>
</ul>
<p>可以像下面这样使用上面扩展的 LiveData 对象：</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onActivityCreated</span><span class="params">(savedInstanceState: <span class="type">Bundle</span>?)</span></span> &#123;</span><br><span class="line">    <span class="keyword">super</span>.onActivityCreated(savedInstanceState)</span><br><span class="line">    <span class="keyword">val</span> myPriceListener: LiveData&lt;BigDecimal&gt; = ...</span><br><span class="line">    myPriceListener.observe(<span class="keyword">this</span>, Observer&lt;BigDecimal&gt; &#123; price: BigDecimal? -&gt;</span><br><span class="line">        <span class="comment">// Update the UI.</span></span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="转换-LiveData"><a href="#转换-LiveData" class="headerlink" title="转换 LiveData"></a>转换 LiveData</h3><blockquote>
<p>有时候希望在将 LiveData 对象分发给观察者之前对其中存储的值进行更改 ，或者可能需要此 LiveData 根据另一个实例的值返回其他实例。在这种场景下，Lifecycle 中包提供的 Transformations 包含支持这些方案的辅助方法和类。</p>
</blockquote>
<ul>
<li><p>Transformations.map()</p>
<blockquote>
<p>对存储在 LiveData 对象中的值应用一个转换函数，并将结果传播到下游。</p>
</blockquote>
</li>
</ul>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">val</span> userLiveData: LiveData&lt;User&gt; = UserLiveData()</span><br><span class="line"><span class="keyword">val</span> userName: LiveData&lt;String&gt; = Transformations.map(userLiveData) &#123;user -&gt;</span><br><span class="line">    <span class="string">"<span class="subst">$&#123;user.name&#125;</span> <span class="subst">$&#123;user.lastName&#125;</span>"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><p>Transformations.switchMap()</p>
<blockquote>
<p>类似于 map()，将一个函数应用于存储在 LiveData 对象中的值，并将结果解包并调度到下游。传递给 switchMap() 参数的这个函数，必须返回一个LiveData对象，如下例所示：</p>
</blockquote>
</li>
</ul>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">getUser</span><span class="params">(id: <span class="type">String</span>)</span></span>: LiveData&lt;User&gt; &#123;</span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">val</span> userId: LiveData&lt;String&gt; = ...</span><br><span class="line"><span class="keyword">val</span> user = Transformations.switchMap(userId) &#123; id -&gt; getUser(id) &#125;</span><br></pre></td></tr></table></figure>
<h3 id="合并多个-LiveData-源"><a href="#合并多个-LiveData-源" class="headerlink" title="合并多个 LiveData 源"></a>合并多个 LiveData 源</h3><ul>
<li><p>MediatorLiveData</p>
<blockquote>
<p>MediatorLiveData 是一个 LiveData 的子类，允许合并多个 LiveData 源。MediatorLiveData 只要其中任何一个原始 LiveData 源对象发生更改，就会触发 MediatorLiveData 对象的观察者。</p>
</blockquote>
</li>
</ul>
<p>例如，如果一个 LiveData 可以从本地数据库或网络更新的对象，则可以将以下源添加到该 MediatorLiveData 对象：</p>
<ul>
<li><p>一个与存储在数据库中的数据关联的 LiveData 对象。</p>
</li>
<li><p>一个与从网络访问的数据关联的 LiveData 对象。</p>
</li>
</ul>
<p>此时，UI 中只需要观察 MediatorLiveData 对象，就可以做到观察两个数据源的更新。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>============ END ============</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="段燚涛 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="段燚涛 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Jetpack/" rel="tag"># Jetpack</a>
          
            <a href="/tags/LiveData/" rel="tag"># LiveData</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/04/09/DataBinding - 使用可观察的数据对象/" rel="next" title="DataBinding - 使用可观察的数据对象">
                <i class="fa fa-chevron-left"></i> DataBinding - 使用可观察的数据对象
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/04/12/Jetpack-之-MVVM/" rel="prev" title="Jetpack 之 MVVM">
                Jetpack 之 MVVM <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MzUzNC8yMDA3Mw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpeg" alt="段燚涛">
            
              <p class="site-author-name" itemprop="name">段燚涛</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">17</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/duanyitao" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:duanyitao7937@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                快速链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/googlesamples/android-architecture/tree/todo-mvvm-databinding/todoapp" title="Android-architecture" target="_blank">Android-architecture</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://developer.android.google.cn/jetpack" title="Jetpack" target="_blank">Jetpack</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是-LiveData"><span class="nav-number">1.</span> <span class="nav-text">什么是 LiveData</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用-LiveData-的好处"><span class="nav-number">2.</span> <span class="nav-text">使用 LiveData 的好处</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#UI-和数据保持一致性"><span class="nav-number">2.1.</span> <span class="nav-text">UI 和数据保持一致性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#没有内存泄漏"><span class="nav-number">2.2.</span> <span class="nav-text">没有内存泄漏</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#不会因-UI-暂停而崩溃"><span class="nav-number">2.3.</span> <span class="nav-text">不会因 UI 暂停而崩溃</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#不再需要手动管理生命周期"><span class="nav-number">2.4.</span> <span class="nav-text">不再需要手动管理生命周期</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#始终保持最新数据"><span class="nav-number">2.5.</span> <span class="nav-text">始终保持最新数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#配置更改自动处理"><span class="nav-number">2.6.</span> <span class="nav-text">配置更改自动处理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#共享资源"><span class="nav-number">2.7.</span> <span class="nav-text">共享资源</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#如何使用-LiveDate-对象"><span class="nav-number">3.</span> <span class="nav-text">如何使用 LiveDate 对象</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建-LiveData-对象"><span class="nav-number">3.1.</span> <span class="nav-text">创建 LiveData 对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#观察-LiveData-对象"><span class="nav-number">3.2.</span> <span class="nav-text">观察 LiveData 对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#更新-LiveData-对象"><span class="nav-number">3.3.</span> <span class="nav-text">更新 LiveData 对象</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#LiveData-高级部分"><span class="nav-number">4.</span> <span class="nav-text">LiveData 高级部分</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#在-Room-中使用-LiviData"><span class="nav-number">4.1.</span> <span class="nav-text">在 Room 中使用 LiviData</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#扩展-LiviData"><span class="nav-number">4.2.</span> <span class="nav-text">扩展 LiviData</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#转换-LiveData"><span class="nav-number">4.3.</span> <span class="nav-text">转换 LiveData</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#合并多个-LiveData-源"><span class="nav-number">4.4.</span> <span class="nav-text">合并多个 LiveData 源</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Build by duanyitao.</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">38.6k</span>
  
</div>









        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.4"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.4"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.4"></script>


</body>
</html>
